<template>
  <el-dialog
    v-model="visibility"
    :title="props.rowData.id ? config.button.text.edit : config.button.text.add"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="米厂全称"
            prop="fullName">
            <el-input
              v-model="formData.fullName"
              clearable
              placeholder="米厂全称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="米厂简称"
            prop="simpleName">
            <el-input
              v-model="formData.simpleName"
              clearable
              placeholder="米厂简称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="启用状态"
            prop="isEnable">
            <el-select
              v-model="formData.isEnable"
              placeholder="启用状态"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                :label="config.button.text.stop"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="备注信息"
            prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              clearable
              placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="资质图片"
            prop="fileDataJson">
            <!-- <div> -->
            <!-- <el-upload
                    :file-list="[]"
                    :headers="headers"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-success="handleFileSuccess"
                    name="files"
                  >
                    <el-button type="primary">上传</el-button>
                  </el-upload> -->
            <UploadFile
              ref="uploadRef"
              :show="true"
              :file-uuids="fileDataList"
              @success="success"
              @delete-file="deleteFile" />
            <!-- </div> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
    <el-dialog
      title="预览"
      v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image" />
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiBaseRiceBarn from "@/api/modules/base-rice-barn";
import { useValidator } from "@/hooks/useValidator";
import message from "@/common/element-plus/message";
import axios from "axios";
import loadon from "@/common/element-plus/loadon";
import { ElLoading } from "element-plus";
import UploadFile from "@/components/UploadFile.vue"

const visibility = ref(false)
const formData = ref({})
const formRef = ref()
const { required, validate, clearValidate } = useValidator()
const token = localStorage.getItem(localStorage.getItem("tokenName"))
const headers = ref({});
const loadingInstance = ref(null);
const isDropdownVisible = ref(false);
if (token) {
  headers.value["yg-token"] = token;
}
const uploadUrl = ref(import.meta.env.VITE_API+"/businessFile/uploadFile");

const formRules = {
  fullName: [required("米厂全称")],
  simpleName: [required("米厂简称")],
}

const props = defineProps(["rowData"]);
const fileDataList = ref();
const imageList = ref([]);
const dialogImageUrl = ref();
const dialogVisible = ref(false)

const emits = defineEmits(["save"]);

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    formData.value = props.rowData;
    imageList.value = [];
    fileDataList.value = []
    if (formData.value.fileDataJson&&Array.isArray(JSON.parse(formData.value.fileDataJson))){
      fileDataList.value = JSON.parse(formData.value.fileDataJson);
      // if(fileDataList.value.length>0){
      //   getImageList();
      // }
    } else {
      imageList.value = []
    }
    setTimeout(() => {
      clearValidate(formRef.value)
    })
  }
}, { immediate: true })

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

//保存
const saveEvent = async () => {
  await validate(formRef.value)
  formData.value.fileDataJson = JSON.stringify(fileDataList.value)
  if (formData.value.id) {
    await ApiBaseRiceBarn.update(formData.value)
  } else {
    await ApiBaseRiceBarn.insert(formData.value)
  }
  emits("save")
}

//预览图片
const previewImg = async (info) => {
  try {
    loadingInstance.value = ElLoading.service({
      lock: true,
      text: "加载...",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)"
    });
    const response = await axios.get(`${import.meta.env.VITE_API}/businessFile/Preview?fileUuid=${info.fileUuid}`, {
      responseType: "blob",
      headers: {
        "yg-token": token  // 根据后端要求设置 Token 头部
      }
    });
    const blob = new Blob([response.data], { type: response.headers["content-type"] });
    const imageUrl = URL.createObjectURL(blob);
    dialogImageUrl.value = imageUrl
    dialogVisible.value = true
    loadingInstance.value.close();
  } catch (error) {
    message.error("获取图片失败:", error);
    loadingInstance.value.close();
  }
}

//处理文件成功回调
const handleFileSuccess = (res, fileList) => {
  if (loadingInstance.value) {
    loadingInstance.value.close();
  }
  if (res?.code===200){
    fileDataList.value.push(res.data[0].fileUuid);
    getImageList();
  } else {
    message.warning(res?.message);
  }
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
  .el-row {
    align-items: flex-start;
  }
 
  @media screen and (max-width: 700px) {
    :deep(.el-form-item__label) {
      width: 100px !important;
    }
  }
</style>
